// 配置API接口地址
var root = "";
var qs = require("querystring"); // qs序列化，解决data传参，后台无法接受的问题
// 引用axios
import axios from "axios";
import router from "../router";
import store from "../store/index";
// const token=localStorage.getItem('token');
//创建axios实例
var service = axios.create({
  baseURL: root,
  timeout: 5000

  // headers: {
  //     'content-type': 'application/x-www-form-urlencoded',
  //     // "Authorization":  token
  // },
});

service.interceptors.request.use(
  config => {
    // console.log('config.headers',config.headers);
    let token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// service.interceptors.response.use(function(response) {
//   // 响应成功则直接返回数据

//   //   console.log(response)
//   if (!response.data.success && response.data.code == "UnLogin") {
//     store.commit("show", true);

//     router.push({ path: "/" });
//   }

//   return response;
// });

function apiAxios(method, url, param) {
  return new Promise((cback, reject) => {
    service({
      method,
      url,
      data: method === "POST" || method === "PUT" ? qs.stringify(param) : null,
      params: method === "GET" || method === "DELETE" ? param : null,
      withCredentials: false
    })
      .then(res => {
        //axios返回的是一个promise对象

        var res_code = res.status.toString();
        if (res_code.charAt(0) == 2) {
          cback(res); //cback在promise执行器内部
        } else {
          console.log(res, "异常1");
        }
      })
      .catch(err => {
        if (!err.response) {
          console.log(err);
          console.log("请求错误err.response");
        } else {
          reject(err.response);
          console.log(err.response, "异常2");
        }
      });
  });
}
export default {
  //get请求，其他类型请求复制粘贴，修改method
  get: function(url, param) {
    return apiAxios("GET", url, param);
  },
  post: function(url, param) {
    return apiAxios("POST", url, param);
  },
  put: function(url, param) {
    return apiAxios("PUT", url, param);
  },
  delete: function(url, param) {
    return apiAxios("DELETE", url, param);
  }
};
